package io.gitee.dtdage.app.boot.starter.data.storage.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.region.Region;
import io.gitee.dtdage.app.boot.starter.data.storage.context.Configure;
import io.gitee.dtdage.app.boot.starter.data.storage.enums.Supplier;
import io.gitee.dtdage.app.boot.starter.data.storage.service.ConfigureService;
import io.gitee.dtdage.app.boot.starter.data.storage.service.StorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * 腾讯云对象存储实现类
 *
 * @author WFT
 * @noinspection SpellCheckingInspection
 * @since 2024/4/14
 */
@Service
@RequiredArgsConstructor
public class TencentStorageServiceImpl implements StorageService {

    private final ConfigureService<?> configureService;

    @Override
    public Supplier getId() {
        return Supplier.tencent_cloud;
    }

    private COSClient getClient(Configure configure) {
        //  初始化凭据
        BasicCOSCredentials credentials = new BasicCOSCredentials(configure.getSecretId(), configure.getSecretKey());
        //  创建对象存储客户端
        return new COSClient(credentials, new ClientConfig(new Region(configure.getBucketRegion())));
    }

    @Override
    public void delete(String path) {
        //  获取存储桶配置
        Configure configure = this.configureService.getConfigure(this.getId());
        //  删除文件
        this.getClient(configure).deleteObject(configure.getBucketName(), path);
    }

    @Override
    public String upload(InputStream stream, String filename, String suffix) {
        //  获取存储桶配置
        Configure configure = this.configureService.getConfigure(this.getId());
        //  上传文件
        this.getClient(configure).putObject(configure.getBucketName(), filename + suffix, stream, null);
        //  返回访问路径
        return configure.getProxyPath() + filename + suffix;
    }

}
